var _ = require('lodash');
var mkdirp = require('mkdirp');
var fs = require('fs');
var Web3 = require('web3');
var REPORT_FREQUENCY = 1000;//ms

module.exports = function(client, opt, done) {
  if (!client || !client.process) throw new Error('No client process found.');
  var rpc = opt.rpc || 'http://localhost:8545';
  var web3Master = new Web3(new Web3.providers.HttpProvider(rpc));
  const highestBlock = web3Master.eth.blockNumber;
  var usage = require('./usage')(client);
  var poll = (client.rpc === false) ? require('./stdPoll') : require('./rpcPoll');

  logClient(client.process); //true for debug

  if (_.isFunction(opt)) done = opt;

  var finalReport = function(poll) {
    console.log({
      'Process ID': client.process.pid,
      'Associated PIDs': client.associatedPids,
      'Blocks processed:': poll.currentBlock,
      'Sync took:': poll.time.toFixed(3) + 's',
      'Usage (average)': usage.average()
    });
  };


  poll = poll(highestBlock, client, function(err, poll) {
    console.log('done');
    finalReport(poll);
    done(err);
  });

  setInterval(function() {
    if (poll.isActive) {
      usage.profile((err, usage) => {
        if (err) throw err;
        fs.appendFileSync(opt.output, {
          imports: poll.newBlocks,
          blocks: poll.currentBlock + ' / ' + highestBlock,
          cpu: usage.cpu,
          memory: usage.memory,
          time: Math.round(poll.time),
        });
      });
    }
  }, REPORT_FREQUENCY);
};

function logClient(ps, print) {
  mkdirp.sync('./logs');

  var store = (data) => {
    fs.appendFileSync('./logs/' + ps.pid + '.txt', data);
  };

  ps.stdout.on('data', store);
  ps.stderr.on('data', store);

  if (print) {
    ps.stdout.on('data', function(data) {
      console.log('OUT:', data.toString());
    });
    ps.stderr.on('data', function(data) {
      console.log('ERR:', data.toString());
    });
  }
}

